﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using A2DFramework.EventService.Configuration;
using System.Threading;
using A2DFramework.EventService.Providers;
using A2DFramework.InstanceService;
using A2DFramework.EventService.Factory;

namespace A2DFramework.EventService
{
    /// <summary>
    /// 模块启动入口
    /// </summary>
    public static class Starter
    {
        internal static IEventResolver eventResolver = new EventResolver();

        /// <summary>
        /// 对模块进行初始化配置
        /// </summary>
        public static void Init()
        {
            //IoC注入
            switch (EventServiceConfiguration.EventBusType)
            {
                case EventBusType.Local:
                    ObjectFactory.RegisterAsSingleton<IEventBusProvider, LocalEventBusProvider>();
                    break;
                case EventBusType.Redis:
                    ObjectFactory.RegisterAsSingleton<IEventBusProvider, RedisEventBusProvider>();
                    break;
                case EventBusType.SuperSocket:
                    ObjectFactory.RegisterAsSingleton<IEventBusProvider, SuperSocketEventBusProvider>();
                    break;
            }

            ObjectFactory.RegisterAsSingleton<IEventBus, EventBusService>();

            EventQueueProcessor qp = new EventQueueProcessor();
            ThreadPool.QueueUserWorkItem(new WaitCallback(qp.Process));

            Thread.Sleep(200);

            RegisterEvents();
        }

        internal static void RegisterEvents()
        {
            IEventBusProvider provider = ObjectFactory.Resolve<IEventBusProvider>();

            foreach (var map in EventServiceConfiguration.EventMappings)
            {
                provider.Subscribe(map.Event);
            }
        }
    }
}
